<?php
/**
 * Created by PhpStorm
 * User: ZhuYunlong2018
 * Email: 920200256@qq.com
 * Date: 2021/4/22
 * Time: 11:41
 */

namespace app\admin\annotation;

use app\lib\exception\DevException;
use Doctrine\Common\Annotations\Annotation;
use Doctrine\Common\Annotations\Annotation\Enum;
use Doctrine\Common\Annotations\Annotation\Target;


/**
 * 注册权限注解类
 * @package topthink\annotation
 * @Annotation
 * @Target({"METHOD","CLASS"})
 */
class Permission extends Annotation implements CheckAnnotation
{
    /**
     * 权限api说明
     * @var string
     */
    public $desc;

    /**
     * 权限类别：OPEN：分为开放、TOKEN：需要登录token、AUTH：需要管理分配权限
     * @Enum({"OPEN","TOKEN","AUTH"})
     * @var string
     */
    public $type;

    /**
     * 请求类型
     * @Enum({"GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"})
     * @var string
     */
    public $method = "*";

    /**
     * 权限key，默认为控制器:方法，例如"Index::index"，不需要开发者手动注入
     * @var string
     */
    public $key;

    /**
     * 校验器，由"@Validate"注解进行添加， 不要手动指定
     * @var Validate
     */
    public $validate;

    /**
     * 校验注解类使用是否符合规范
     * @param string $class
     * @return mixed
     * @throws DevException
     */
    function check(string $class)
    {
        if (trim($this->desc) === "") {
            throw new DevException($class . '注解desc描述不能为空');
        }
        if (!in_array($this->type, [
            'OPEN',
            'TOKEN',
            'AUTH'
        ])) {
            throw new DevException($class . '注解type类型不正确');
        }
        if (!in_array($this->method, [
            '*',
            "GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"
        ])) {
            throw new DevException($class . '注解method不正确');
        }
        if (!empty($this->key)) {
            throw new DevException($class . '权限key不需要自定义');
        }
    }
}